package com.tsd.system.utils;

import com.tsd.core.cache.CacheConstants;
import com.tsd.core.constants.JwtConstants;
import com.tsd.core.vo.HlpException;
import com.tsd.system.entity.SysUserExt;
import io.jsonwebtoken.Claims;

/**
 * @Description:
 * @Author Hillpool
 * @Date 2019/3/12 14:36
 * @Modefied By:
 */
public class SysUtil {

    /**
     * 从Claims中获取sysUser信息
     *
     * @param claims
     * @return
     * @throws HlpException
     */
    public static SysUserExt getSysUserFromClaims(Claims claims) throws HlpException {
        if (claims != null) {
            SysUserExt opUser = new SysUserExt();
            String userId = (String) claims.get(JwtConstants.CLAIM_NAME_SID);
            String userName = (String) claims.get(JwtConstants.CLAIM_NAME_USER_NAME);
            String loginId = (String) claims.get(JwtConstants.CLAIM_NAME_LOGIN_ID);
            String groupSid = (String) claims.get(JwtConstants.CLAIM_NAME_GROUP_SID);
            String groupPersonSid = (String) claims.get(JwtConstants.CLAIM_NAME_GROUP_PERSON_SID);
            String accountSetSid = (String) claims.get(JwtConstants.CLAIM_NAME_ACCOUNT_SET_SID);
            String type = (String) claims.get(JwtConstants.CLAIM_NAME_TYPE);
            String clientSid = (String) claims.get(JwtConstants.TYPE_CLIENT_OPERATOR);
            String openId = (String) claims.get(JwtConstants.CLAIM_NAME_OPEN_ID);
            String clientAuthMode = (String) claims.get(JwtConstants.CLAIM_NAME_CLIENT_AUTH_MODE);
            String clientAuthSetting = (String) claims.get(JwtConstants.CLAIM_NAME_CLIENT_AUTH_SETTING);
            String deviceType = (String) claims.get(JwtConstants.CLAIM_NAME_DEVICE_TYPR);
            opUser.setSid(userId);
            opUser.setName(userName);
            opUser.setLogin_id(loginId);
            opUser.setGroup_sid(groupSid);
            opUser.setGroup_person_sid(groupPersonSid);
            opUser.setAccount_set_sid(accountSetSid);
            opUser.setToken_type(type);
            opUser.setClient_sid(clientSid);
            opUser.setOpen_id(openId);
            opUser.setClient_auth_mode(clientAuthMode);
            opUser.setClient_auth_setting(clientAuthSetting);
            opUser.setDevice_type(deviceType);
            return opUser;
        } else {
            throw new HlpException("令牌无效，请重新登录");
        }
    }

    public static String getTokenCacheKey(String dataSource, SysUserExt userExt) {
        return dataSource + CacheConstants.CACHE_DELIMITER + userExt.getDevice_type() +
                CacheConstants.CACHE_DELIMITER + userExt.getSid();
    }

}
